Imports System.IO
Imports System.IO.Ports.SerialPort

Public Class Advia2120
    Public Const Advia2120InitMessage As String = "0I "

    Public Function StringChecksum(ByVal sInput As String) As Byte
        Dim bSTemp() As Char
        Dim bChecksum As Byte
        bSTemp = sInput.ToCharArray()
        bChecksum = Asc(bSTemp(0))
        Dim i As Int16
        For i = 1 To bSTemp.GetLength(0) - 1
            bChecksum = bChecksum Xor Asc(bSTemp(i))
        Next i
        If bChecksum <> &H3 Then
            Return bChecksum
        Else
            Return &H7F
        End If
    End Function

    Public Sub MessageParse(ByVal sInput As String, ByRef bMT As Byte, ByRef sID As Char, ByRef sData As String)

        Dim sTemp() As String
        sTemp = sInput.Split(Chr(ETX))
        'sTemp = sInput.Split(Chr(STX))
        bMT = Asc(sTemp(0).Substring(0, 1))
        sID = sTemp(0).Substring(1, 1)
        sData = sTemp(0).Substring(2)

    End Sub

    'S Message: Token Transfer
    Public Function CreateSMessage(ByVal bMT As Byte) As String
        Dim sTmp, sTmp1 As String
        sTmp = [String].Concat(Chr(bMT), "S", Space(10), vbCrLf)
        Dim cChecksum As Char = Chr(StringChecksum(sTmp))
        sTmp1 = [String].Concat(Chr(STX), sTmp, cChecksum, Chr(ETX))
        Return sTmp1
    End Function

    'Z Message: Result Validation 
    Public Function CreateZMessage(ByVal bMT As Byte) As String
        Dim sTmp, sTmp1 As String
        sTmp = [String].Concat(Chr(bMT), "Z", Space(17), " 0" & vbCrLf)
        Dim cChecksum As Char = Chr(StringChecksum(sTmp))
        sTmp1 = [String].Concat(Chr(STX), sTmp, cChecksum, Chr(ETX))
        Return sTmp1
    End Function

    'I Message: Initation
    Public Function CreateIMessage(ByVal bMT As Byte) As String
        Dim sTmp, sTmp1 As String
        sTmp = [String].Concat(Advia2120InitMessage & vbCrLf)
        Dim cChecksum As Char = Chr(StringChecksum(sTmp))
        sTmp1 = [String].Concat(Chr(STX), sTmp, cChecksum, Chr(ETX))
        Return sTmp1

    End Function

    Public Sub ResultParse(ByVal sInput As String)
        Dim f As File
        f.AppendAllText("C:\Advia2120_result.txt", Now.ToString & vbCrLf & sInput & vbCrLf & vbCrLf)
    End Sub

End Class